package com.li.springboard.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

@Configuration
public class DruidConfig {
    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDatasource(){
        return new DruidDataSource();
    }

    /**
     * druid后台监控
     * @return
     */
    @Bean
    public ServletRegistrationBean statViewServlet(){
        ServletRegistrationBean<StatViewServlet> bean=new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");

        HashMap<String,String> init=  new HashMap<>();
        //后台需要有人登录
        init.put("loginUsername","admin");
        init.put("loginPassword","1234");

        //允许谁可以访问
        init.put("allow","");
        //禁止谁可以访问   init.put("jaksd","IP地址");

        //设置初始化参数
        bean.setInitParameters(init);

        return bean;
    }

    /**
     * druid过滤器
     * @return
     */
    @Bean
    public FilterRegistrationBean webStatFilter(){
        FilterRegistrationBean bean =new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //可以过滤那些请求
        Map<String ,String> init=new HashMap<>();
        //这些东西不进行统计
        init.put("exclusions","*.js,/druid/**");

        bean.setInitParameters(init);
        return bean;
    }
}
